package com.csaba.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class IntervalDates
{

	private final int interval;
	private final int from;
	private final int to;

	public int getInterval()
	{
		return interval;
	}

	public int getFrom()
	{
		return from;
	}

	public int getTo()
	{
		return to;
	}

	public int getDate( final Date date )
	{
		final Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		return getDate(calendar);
	}

	public int getDate( final Calendar date )
	{
		final int iDate = date.get(Calendar.YEAR) * 10000 + ( date.get(Calendar.MONTH) + 1 ) * 100
				+ date.get(Calendar.DATE);
		return iDate;
	}

	public boolean isInInterval( final int date )
	{
		return from <= date && date <= to;
	}

	public boolean isInInterval( final Date date )
	{
		return isInInterval(getDate(date));
	}

	public IntervalDates( int interval, final boolean includeToday )
	{
		this.interval = interval;
		final Calendar currDate = Calendar.getInstance();
		if ( !includeToday )
		{
			currDate.add(Calendar.DATE, -1);
			interval--;
		}
		this.to = getDate(currDate);
		currDate.add(Calendar.DATE, -interval);
		this.from = getDate(currDate);
	}

	/**
	 * @param args
	 */
	public static void main( final String[] args )
	{
		try
		{
			final SimpleDateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy");
			final Date from = dateFormat.parse(args[0]); //e.g.: 16.10.2008
			final Date to = dateFormat.parse(args[1]);

			final IntervalDates iDates = new IntervalDates(90, false);
			System.out.println("Interval: " + iDates.getFrom() + " - " + iDates.getTo());
			System.out.println("From - To: " + iDates.getDate(from) + " - " + iDates.getDate(to));
			System.out.println("From is in the interval: " + iDates.isInInterval(from));
			System.out.println("To is in the interval: " + iDates.isInInterval(to));
		}
		catch ( final ParseException ex )
		{
			System.out.println("ParseException: " + ex.getMessage());
		}
	}

}
